﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.Net;
using System.Configuration;
using SPListsCaller.WS;
using System.Web.Services.Protocols;
using ElkiTools.SPListCaller.Core.Exceptions;

namespace EspaceCo.Console.SPWebServices
{
    public static class ListsWS
    {
        public static XmlNode GetListItems_ByQuery(
            string wsUrl,
            GetListItems_CallParameters queryData,
            NetworkCredential credential,
            WebProxy proxy)
        {
            GetListItems_CallParameters nextPageCallParams;
            return GetListItems_ByQuery(wsUrl, queryData, credential, proxy, out nextPageCallParams);
        }

        public static XmlNode GetListItems_ByQuery(
            string wsUrl,
            GetListItems_CallParameters queryData,
            NetworkCredential credential,
            WebProxy proxy,
            out GetListItems_CallParameters nextPageCallParams)
        {
            XmlNode result = null;
            nextPageCallParams = null;
            //-------------------------------------------------------------------------------------------------------

            using (SPListCaller.WS.Proxies.Lists listService = new SPListCaller.WS.Proxies.Lists())
            {
                // Url
                listService.Url = wsUrl;

                // Proxy
                if (proxy != null)
                {
                    listService.Proxy = proxy;
                }

                // Credentiels
                listService.UseDefaultCredentials = false;
                listService.Credentials = credential;

                // Préparation de la requête
                XmlDocument xDoc = new XmlDocument();
                XmlNode ndQuery = xDoc.CreateElement("Query");
                XmlNode ndViewFields = xDoc.CreateElement("ViewFields");
                XmlNode ndQueryOptions = xDoc.CreateElement("QueryOptions");

                // Check si on doit surchager les paramètres de la vue par défaut
                // http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems.aspx
                bool bOverrideViewParams = string.IsNullOrEmpty(queryData.ViewName);

                if (!string.IsNullOrEmpty(queryData.Query))
                    ndQuery.InnerXml = "" + queryData.Query;
                else if(bOverrideViewParams)
                    ndQuery.InnerXml = "<Where/>";

                if (!string.IsNullOrEmpty(queryData.ViewFields))
                    ndViewFields.InnerXml = "" + queryData.ViewFields;
                else if (bOverrideViewParams)
                    ndViewFields.InnerXml = "<FieldRef Name=\"ID\"/>";

                if (!string.IsNullOrEmpty(queryData.QueryOptions))
                    ndQueryOptions.InnerXml = "" + queryData.QueryOptions;

                // Appel
                try
                {
                    result = listService.GetListItems(
                        queryData.ListName,
                        string.IsNullOrEmpty(queryData.ViewName) ? null : queryData.ViewName,
                        ndQuery,
                        ndViewFields,
                        (queryData.RowLimit <= 0) ? null : queryData.RowLimit.ToString(),
                        ndQueryOptions,
                        null);

                }
                catch (SoapException excSoap)
                {
                    throw new WSCallException(string.Empty, excSoap);
                }
                catch (Exception exc)
                {
                    throw new WSCallException(string.Empty, exc);
                }

                // Gestion de la pagination
                try
                {
                    if (result != null)
                    {
                        nextPageCallParams = queryData.GetNextPagedCallParameter(result);
                    }
                }
                catch (Exception excPaging)
                {
                    throw new WSCallException("Une erreur est survenue lors de la création du nouveau GetListItems_CallParameters pour la pagination.", excPaging);
                }
            }

            //-------------------------------------------------------------------------------------------------------
            return result;
        }
    }
}
